<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getequipmentlist } from '@/api/echarts'

export default {
  name: "map-view",
  data() {
    return {
      map: null,
      markers: [],
      cluster: null,
    };
  },
  created() {
    this.fetchEquipmentList();
  },
  mounted() {
    // 移除这里的 initAMap 调用，因为我们会在 fetchEquipmentList 方法中调用它
    // this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    fetchEquipmentList() {
      getequipmentlist({ limit: 10000000 }).then(res => {
        console.log(res, "研究地图");
        // 提取所有对象的 lat 和 lng 属性，并跳过无效的经纬度
        this.markers = res.msg
          .filter(item => item.lat && item.lng) // 过滤掉没有经纬度的数据
          .map(item => {
            return new AMap.Marker({
              position: new AMap.LngLat(item.lng, item.lat)
            });
          });
        // 初始化地图并添加聚合
        this.initAMap();
      }).catch(error => {
        console.error('Error fetching equipment list:', error);
      });
    },
    initAMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c", // 申请好的Web端开发者Key
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.Scale", "AMap.MarkerClusterer"], // 需要使用的插件列表
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            viewMode: "3D", // 是否为3D地图模式
            zoom: 4, // 初始化地图级别
            center: [116.397428, 39.90923], // 初始化地图中心点位置
            mapStyle: "amap://styles/blue", // 使用高德提供的地图样式
          });

          // 添加比例尺
          this.map.addControl(new AMap.Scale());

          // 创建并添加标记聚合
          this.cluster = new AMap.MarkerClusterer(this.map, this.markers, {
            gridSize: 80,
            renderClusterMarker: this.renderClusterMarker,
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    renderClusterMarker(context) {
      const count = context.count;
      const div = document.createElement("div");
      div.className = "amap-cluster";
      div.style.backgroundColor = "rgba(255, 0, 0, 0.6)";
      div.style.border = "solid 1px rgba(255, 0, 0, 1)";
      div.style.borderRadius = "50%";
      div.style.width = div.style.height = `${Math.sqrt(count) * 10}px`;
      div.style.lineHeight = div.style.height;
      div.style.color = "#fff";
      div.style.textAlign = "center";
      div.innerHTML = count;
      context.marker.setContent(div);
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100vh;
}
.amap-cluster {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
